﻿
#include <QJsonValue>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonParseError>
#include <QDebug>
#include "loader.h"
#include "event.h"
#include "plan.h"
#include <QDir>
#include <QDebug>
#include <QTime>
void Loader::chk_crtDir() {
    QDir dir("./");
    dir.mkpath("savings");
    dir.mkpath("savings/todolists");
}

QVector<Event> Loader::loadEvents(QString path) {
    chk_crtDir();
    QVector<Event> events;
    QFile file(path);
    file.open(QIODevice::ReadOnly);
    if(!file.isOpen()) {
        return QVector<Event>();
    }
    QJsonParseError json_error;
    QJsonDocument doc = QJsonDocument::fromJson(QByteArray(file.readAll()),&json_error);
    file.close();
    if(json_error.error!=QJsonParseError::NoError) {
        qDebug()<<QString("error occurred when loading events:")+json_error.errorString();
        return QVector<Event>();
    }
    QJsonArray array = doc.array();
    for(int i = 0; i<array.count(); i++) {
        QJsonObject obj = array.at(i).toObject();
        if(!obj.contains("name")||!obj.contains("description")
                ||!obj.contains("bellRing")||!obj.contains("people")||!obj.contains("time")||!obj.contains("importance")||!obj.contains("needRing")) {
            qDebug()<<QString("error occurred when loading events:wrong json content ");
            return QVector<Event>();
        }
        Event event;
        event.setName(obj.take("name").toString());
        event.setDescription(obj.take("description").toString());
        event.setTime(QDateTime::fromMSecsSinceEpoch(obj.take("time").toInt()));
        event.setBellRing(BellRings(obj.take("bellRing").toInt()));
        event.setImportance(obj.take("importance").toInt());
//        event.setImportance(obj.take("importace").toInt());
        event.setNeedRing(obj.take("needRing").toBool());
        QJsonArray peopleNames = obj.take("people").toArray();
        for(int j = 0; j<peopleNames.count(); j++)event.addPerson(peopleNames.at(i).toString());
        events.append(event);
    };
    return events;
}

QVector<Plan> Loader::loadPlans(QString path) {
    chk_crtDir();
    QVector<Plan> plans;
    QFile file(path);
    file.open(QIODevice::ReadOnly);
    if(!file.isOpen()) {
        return QVector<Plan>();
    }
    QJsonParseError json_error;
    QJsonDocument doc = QJsonDocument::fromJson(QByteArray(file.readAll()),&json_error);
    file.close();
    if(json_error.error!=QJsonParseError::NoError) {
        qDebug()<<QString("error occurred when loading plans:")+json_error.errorString();
        return QVector<Plan>();
    }
    QJsonArray array = doc.array();
    for(int i = 0; i<array.count(); i++) {
        QJsonObject obj = array.at(i).toObject();
        Plan plan;
        plan.setName(obj.take("name").toString());
        plan.setType(PlanType(obj.take("planType").toInt()));
        plan.setFinish_if_week(obj.take("finish_if_week").toBool());
        QJsonArray events = obj.take("events").toArray();
        for(int j = 0; j<events.count(); j++) {
            QJsonObject obj = events.at(j).toObject();
            if(!obj.contains("name")||!obj.contains("description")
                    ||!obj.contains("bellRing")||!obj.contains("people")||!obj.contains("time")) {
                qDebug()<<QString("error occurred when loading plan_event:wrong json content ");
                return QVector<Plan>();
            }
            Event event;
            event.setName(obj.take("name").toString());
            event.setDescription(obj.take("description").toString());
            event.setTime(QDateTime::fromMSecsSinceEpoch(obj.take("time").toInt()));
            event.setBellRing(BellRings(obj.take("bellRing").toInt()));
            QJsonArray peopleNames = obj.take("people").toArray();
            for(int j = 0; j<peopleNames.count(); j++)event.addPerson(peopleNames.at(i).toString());
            plan.addEvent(event);
        }
        plans.append(plan);
    }
    return plans;
}

QVector<TODOList> Loader::loadTODOList(QString path) {
    chk_crtDir();
    QVector<TODOList> lists;
    QFile file(path);
    file.open(QIODevice::ReadOnly);
    if(!file.isOpen()) {
        return QVector<TODOList>();
    }
    QJsonParseError json_error;
    QJsonDocument doc = QJsonDocument::fromJson(QByteArray(file.readAll()),&json_error);
    file.close();
    if(json_error.error!=QJsonParseError::NoError) {
        qDebug()<<QString("error occurred when loading plans:")+json_error.errorString();
        return QVector<TODOList>();
    }
    QJsonArray array = doc.array();
    for(int i = 0; i<array.count(); i++) {
        QJsonObject obj = array.at(i).toObject();
        TODOList list;
        list.setName(obj.take("name").toString());
        QJsonArray items = obj.take("items").toArray();
        for(int j = 0; j<items.count(); j++) {
            QJsonObject item = items.at(j).toObject();
            TODOItem itm;
            itm.setName(item.take("name").toString());
            itm.setExplanation(item.take("explanation").toString());
            list.addTODOItem(itm);
        }
        lists.append(list);
    }
    return lists;
}
void Loader::saveEvents(QVector<Event> &events,QString path) {
    QFile file(path);
    chk_crtDir();
    QJsonArray array;
    for(auto &x:events) {
        QJsonObject obj;
        obj.insert("name",x.getName());
        obj.insert("description",x.getDescription());
        obj.insert("time",x.getTime().toMSecsSinceEpoch());
        obj.insert("bellRing",x.getBellRing());
        obj.insert("importance",x.getImportance());
        obj.insert("needRing",x.getNeedRing());
        QJsonArray people;
        QVector<QString> peopleNames = x.getPeople();
        for(QString &name:peopleNames) {
            people.append(name);
        }
        obj.insert("people",people);
        array.append(obj);
    }
    file.open(QIODevice::WriteOnly);
    file.write(QJsonDocument(array).toJson());
    file.close();
//    QString str = file.read();
}

void Loader::savePlans(QVector<Plan> &plans,QString path) {
    QFile file(path);
    chk_crtDir();
    QJsonArray array;
    for(auto &x:plans) {
        QJsonObject obj;
        obj.insert("name",x.getName());
        obj.insert("type",(int)x.getType());
        obj.insert("finish_if_week",x.getFinish_if_week());
        QJsonArray events;
        auto eves = x.getEvents();
        for(Event &y:eves.values()) {
            QJsonObject eve;
            eve.insert("name",y.getName());
            eve.insert("description",y.getDescription());
            eve.insert("time",y.getTime().toMSecsSinceEpoch());
            eve.insert("bellRing",(int)y.getBellRing());
            QJsonArray people;
            QVector<QString> names = y.getPeople();
            for(QString &name:names)people.append(name);
            eve.insert("people",people);
            events.append(eve);
        }
        obj.insert("events",events);
        array.append(obj);
    }
    file.open(QIODevice::WriteOnly);
    file.write(QJsonDocument(array).toJson());
    file.close();
}

void Loader::saveTODOList(QVector<TODOList> &todolists,QString path) {
    QFile file(path);
    chk_crtDir();
    QJsonArray array;
    for(auto &x:todolists) {
        QJsonObject obj;
        obj.insert("name",x.getName());
        QJsonArray items;
        for(auto &y:x.getItems()) {
            QJsonObject item;
            item.insert("name",y.getName());
            item.insert("explanation",y.getExplanation());
            items.append(item);
        }
        obj.insert("items",items);
        array.append(obj);
    }
    file.open(QIODevice::WriteOnly);
    file.write(QJsonDocument(array).toJson());
    file.close();
}

void Loader::saveClock(QVector<Clock> &clks, QString path) {
    QFile file(path);
    chk_crtDir();
    QJsonArray array;
    for(auto &x:clks) {
        QJsonObject obj;
        obj.insert("name",x.getName());
        obj.insert("explanation",x.getDescription());
        obj.insert("repeat",x.getRepeat());
        obj.insert("time",x.getTime().msecsSinceStartOfDay());
        array.append(obj);
    }
    file.open(QIODevice::WriteOnly);
    file.write(QJsonDocument(array).toJson());
    file.close();
}
QVector<Clock> Loader::loadClocks(QString path) {
    QVector<Clock> ret;
    QFile file(path);
    file.open(QIODevice::ReadOnly);
    if(!file.isOpen()) {
        return QVector<Clock>();
    }
    QJsonParseError json_error;
    QJsonDocument doc = QJsonDocument::fromJson(QByteArray(file.readAll()),&json_error);
    file.close();
    if(json_error.error!=QJsonParseError::NoError) {
        qDebug()<<QString("error occurred when loading plans:")+json_error.errorString();
        return QVector<Clock>();
    }
    QJsonArray array = doc.array();
    for(int i = 0; i<array.count(); i++) {
        QJsonObject obj = array.at(i).toObject();
        Clock clock;
        clock.setName(obj.take("name").toString());
        clock.setDescription(obj.take("explanation").toString());
        clock.setRepeat(REPEAT(obj.take("repeat").toInt()));
        clock.setTime(QTime::fromMSecsSinceStartOfDay(obj.take("time").toInt()));//2031年会失效
        ret.append(clock);
    }
    return ret;
}
